﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataClient.ClientDatasetTableAdapters;
using System.Data;
using CommonData;
using CommonData.BusinessDataObjects;

namespace DataClient
{
    public class MainUsecase
    {
        const string STR_NOT_SYNC = "Chưa đồng bộ";
        const string STR_IS_SYNC = "Đồng bộ thành công";
        DataTable _TBLConfig = null;
        private DataRow GetConfigOfTable(string tableName)
        {
            DataRow[] lstSelects = _TBLConfig.Select(string.Format("DestTable = '{0}'", tableName));
            if (lstSelects.Length > 0)
                return lstSelects[0];
            else
                return null;
        }

        private void SyncDataFromSourceToDest(DataRow drInfo, string destTable,bool isClearBefore, bool isAllData)
        {
            string sourceConn = drInfo["SourceConnectionString"].ToString();
            int sourceDB = Convert.ToInt32(drInfo["SourceConfigID"].ToString());
            string sourceTable = drInfo["SourceTable"].ToString();
            SynchronizeBO boSync = new SynchronizeBO();
            boSync.SynchronizeSourceData(Convert.ToDecimal(drInfo["ConfigID"].ToString()), sourceConn, sourceDB, sourceTable, destTable, isClearBefore, isAllData);
        }

        public void ProcessSynchronizeData(ClientDataset dsClient, SyncTrackingTableAdapter daSyncTracking, DateTime fromDate, DateTime toDate, bool isClearBefore, bool isAllData)
        {
            CommonDataAccess cmDataAccess = new CommonDataAccess();
            _TBLConfig = cmDataAccess.GetDataTableBySproc("CLIENTDATA_GetAllTablesConfig");
            foreach (ClientDataset.SyncTrackingRow drTrackingRow in dsClient.SyncTracking)
            {
                if (drTrackingRow.Selected && drTrackingRow.Status == STR_NOT_SYNC)
                {
                    try
                    {
                        drTrackingRow.Description = "Bắt đầu đồng bộ";
                        DataRow drInfo = GetConfigOfTable(drTrackingRow.Items);
                        if (drInfo != null)
                        {
                            SyncDataFromSourceToDest(drInfo, drTrackingRow.Items, isClearBefore, isAllData);

                            drTrackingRow.SyncDate = DateTime.Now;
                            drTrackingRow.Status = STR_IS_SYNC;
                            drTrackingRow.Description = "Đã đồng bộ thành công";

                        }
                    }
                    catch (Exception exp)
                    {
                        drTrackingRow.Description = "Thực hiện đồng bộ không thành công";
                    }
                }
            }
            daSyncTracking.Update(dsClient.SyncTracking);
        }
    }
}
